package top.h1234.codesandbox.docker;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.PullResponseItem;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.LogContainerResultCallback;

import java.util.Arrays;
import java.util.List;

/**
 * Java操作Docker示例代码
 */
public class DockerDemo {
    public static void main(String[] args) {
        // Docker客户端
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();

        // 查看是否能ping通
        dockerClient.pingCmd().exec();

        // 拉取镜像
        String imageName = "nginx:latest";
        pullImage(dockerClient, imageName);

        // 创建容器
        CreateContainerResponse createContainerResponse = dockerClient.createContainerCmd(imageName).exec();
        String containerId = createContainerResponse.getId();
        System.out.println(containerId);

        // 启动容器
        dockerClient.startContainerCmd(containerId).exec();

        // 查看所有容器运行状态
        List<Container> containerList = dockerClient.listContainersCmd().withShowAll(true).exec();
        for (Container container : containerList) {
            System.out.println(container);
        }

        // 停止容器
        dockerClient.stopContainerCmd(containerId).exec();

        // 查看容器运行日志
        catContainerLog(dockerClient, containerId);

        // 删除容器（强制删除）
        dockerClient.removeContainerCmd(containerId).withForce(true).exec();

        // 删除镜像（强制删除）
        dockerClient.removeImageCmd(imageName).withForce(true).exec();
    }


    /**
     * 查看容器运行日志
     *
     * @param dockerClient docker客户端
     * @param containerId  容器id
     */
    private static void catContainerLog(DockerClient dockerClient, String containerId) {
        LogContainerResultCallback logContainerResultCallback = new LogContainerResultCallback() {
            @Override
            public void onNext(Frame item) {
                System.out.println("容器运行日志：" + new String(item.getPayload()));
                super.onNext(item);
            }
        };
        try {
            dockerClient.logContainerCmd(containerId)
                    .withStdOut(true)
                    .withStdErr(true)
                    .exec(logContainerResultCallback)
                    .awaitCompletion();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    
    /**
     * 拉取镜像
     *
     * @param dockerClient docker客户端
     * @param imageName    镜像名称
     */
    private static void pullImage(DockerClient dockerClient, String imageName) {
        PullImageCmd pullImageCmd = dockerClient.pullImageCmd(imageName);
        PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
            @Override
            public void onNext(PullResponseItem item) {
                System.out.println("下载镜像：" + item.getStatus());
                super.onNext(item);
            }
        };
        try {
            pullImageCmd.exec(pullImageResultCallback).awaitCompletion();
        } catch (InterruptedException e) {
            System.out.println("下载镜像出错：" + e.getMessage());
            throw new RuntimeException(e);
        }
        System.out.println("下载 " + imageName + " 完成");
    }

}
